package com.manager.student;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

public class StudentController extends Controller {
	private static final int PAGE_SIZE = 10;
	public void index() {
		setAttr("studentPage", Student.me.paginate(getParaToInt(0, 1), PAGE_SIZE));
		render("student.html");
	}

	public void add() {
		setAttr("totalRow", getParaToInt(1));
	}
	@Before(StudentValidator.class)
	public void save() {
		int totalRow = getParaToInt(0) + 1;
		int totalPage = (int) (totalRow / PAGE_SIZE);
		if (totalRow % PAGE_SIZE != 0) {
			totalPage++;
		}
		
		Student s = getModel(Student.class);
		s.put("cdate", new Date());
		s.save();
		redirect("/student/" + totalPage);
	}

	public void edit() {
		setAttr("student", Student.me.findById(getParaToInt(0)));
		setAttr("pageNumber", getParaToInt(1));
	}
	@Before(StudentValidator.class)
	public void update() {
		getModel(Student.class).update();
		redirect("/student/"+ getParaToInt(0));
	}

	public void delete() {
		int pageNum = getParaToInt(1);
		int totalRow = getParaToInt(2);
		int row = totalRow % PAGE_SIZE;

		if (row == 1 && pageNum > 1) {
			pageNum -= 1;
		}
		getModel(Student.class).deleteById(getParaToInt(0));
		redirect("/student/" + pageNum);
	}
}
